package com.yx.modules.api.controller;

import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.common.validator.Assert;
import com.yx.modules.api.Dto.TbUserDto;
import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.service.TbAttentionService;
import com.yx.modules.api.service.TbRewardRecordService;
import com.yx.modules.api.service.TbTokenService;
import com.yx.modules.api.service.TbUserService;
import com.yx.system.entity.SysUser;
import com.yx.system.entity.TdBook;
import com.yx.system.entity.TdCollection;
import com.yx.system.service.SysUserService;
import com.yx.system.service.TdCollectionService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * API授权登录
 * Created by wuye on 2017/11/24.
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
    @Autowired
    private TbUserService userService;

    @Autowired
    private TbTokenService tokenService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TdCollectionService collectionService;

    @Autowired
    private TbAttentionService attentionService;

    @Autowired
    private TbRewardRecordService rewardRecordService;

    @Autowired
    private SysUserService sysUserService;

//    @Autowired
//    private tdr

    /**
     * 登录
     */
    @AuthIgnore
    @PostMapping("login")
    public R login(String mobile, String password) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        //用户登录
        long userId = userService.login(mobile, password);
        //生成token
        Map<String, Object> map = tokenService.createToken(userId);
        map.put("user", userService.foundById(userId));
        return R.ok().put("data",map);
    }

    /*
    *忘记密码
    */
    @AuthIgnore
    @RequestMapping("/updatePassword")
    public R ForgetAndUpdate(String mobile, String password, String code){
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(code, "验证码不能为空");
        //判断验证码是否正确
        String rcode = redisTemplate.opsForValue().get(mobile);
        if (rcode == null) {
            return R.error("验证码过期");
        }
        if (rcode.equals(code)){
            TbUser tbUser = userService.queryByMobile(mobile);
            if (tbUser == null) {
                return R.error("该手机用户尚未注册");
            }
            tbUser.setPassword(DigestUtils.sha256Hex(password));
            userService.update(tbUser);
            //寻找后台账号是否存在作者
            SysUser sysUser = sysUserService.queryByUserName(tbUser.getMobile());
            if (sysUser!=null){
                sysUser.setPassword(tbUser.getPassword());
                sysUserService.updatePssword(sysUser);
            }
            return R.ok();
        }else {
            return R.error("验证码错误");
        }
    }


    /*
    * 显示用户信息
    */
    @RequestMapping("/userInfo")
    public R userInfo(@LoginUser TbUser tbUser){
        //初始化用户DTO对象
        TbUserDto tbUserDto = new TbUserDto();
        //查询用户书架数并赋值
        Integer collectionCount = collectionService.findTotalByUseruuid(tbUser.getUuid());
        //查询用户关注数并赋值
        Integer attentionCount = attentionService.findTotalByUseruuid(tbUser.getUuid());
        //查询用户打赏数并赋值
        Integer rewardCount = rewardRecordService.findTotalByUserid(tbUser.getUserId());
        //注入属性
        tbUserDto.setTbUser(tbUser);
        tbUserDto.setAttentionCount(attentionCount);
        tbUserDto.setBookrackCount(collectionCount);
        tbUserDto.setRewardCount(rewardCount);
        return R.ok().put("data",tbUserDto);
    }


    /*
    *编辑修改用户资料
    */
    @RequestMapping("/updateUser")
    public R updateUser(@LoginUser TbUser user, TbUser user1){
        return userService.updateUser(user,user1);
    }

    /*
    *打赏图书
    */
    @RequestMapping("/rewardBook")
    public R rewardBook(@LoginUser TbUser user,int bookid,int rewardMoney){
        int actualMoney = rewardMoney*100;
        if (user.getBalance()<actualMoney){
            return R.error("账户余额不足，还差"+(rewardMoney*100-user.getBalance())/100+"蝉币");
        }
        return userService.rewardBook(user,bookid,actualMoney);
    }

}
